package com.jshan.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jshan.base.entity.TableInfo;
import com.jshan.mapper.TableInfoMapper;
import com.jshan.service.TableInfoService;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import com.jshan.base.dto.TableCreateRequest;
import com.jshan.base.dto.TableFieldDTO;
import com.jshan.base.dto.TableIndexDTO;

@Service
public class TableInfoServiceImpl implements TableInfoService {

    @Resource
    private TableInfoMapper tableInfoMapper;

    @Override
    public IPage<TableInfo> getTableList(Integer page, Integer pageSize, String tableName) {
        Page<TableInfo> pageParam = new Page<>(page, pageSize);
        return tableInfoMapper.selectTableList(pageParam, tableName);
    }

    @Override
    public void createTable(TableCreateRequest request) {
        // 判断表是否存在
        Integer count = tableInfoMapper.countTableByName(request.getTableName());
        if (count != null && count > 0) {
            throw new RuntimeException("表已存在");
        }
        // 拼接建表SQL
        StringBuilder sql = new StringBuilder();
        sql.append("CREATE TABLE ").append(request.getTableName()).append(" (");
        for (int i = 0; i < request.getFields().size(); i++) {
            TableFieldDTO field = request.getFields().get(i);
            sql.append(field.getName()).append(" ").append(field.getType());
            if (field.getLength() != null && field.getLength() > 0) {
                sql.append("(").append(field.getLength()).append(")");
            }
            if (Boolean.TRUE.equals(field.getNotNull())) {
                sql.append(" NOT NULL");
            }
            if (Boolean.TRUE.equals(field.getAutoIncrement())) {
                sql.append(" AUTO_INCREMENT");
            }
            if (field.getDefaultValue() != null && !field.getDefaultValue().isEmpty()) {
                sql.append(" DEFAULT '").append(field.getDefaultValue()).append("'");
            }
            if (field.getComment() != null && !field.getComment().isEmpty()) {
                sql.append(" COMMENT '").append(field.getComment()).append("'");
            }
            if (i < request.getFields().size() - 1) {
                sql.append(", ");
            }
        }
        // 主键
        boolean hasPrimary = request.getFields().stream().anyMatch(TableFieldDTO::getPrimaryKey);
        if (hasPrimary) {
            sql.append(", PRIMARY KEY (");
            sql.append(request.getFields().stream().filter(TableFieldDTO::getPrimaryKey).map(TableFieldDTO::getName)
                    .reduce((a, b) -> a + "," + b).get());
            sql.append(")");
        }
        // 索引
        if (request.getIndexes() != null) {
            for (TableIndexDTO idx : request.getIndexes()) {
                sql.append(", ");
                if (Boolean.TRUE.equals(idx.getUnique())) {
                    sql.append("UNIQUE ");
                }
                sql.append("KEY ").append(idx.getName()).append(" (");
                sql.append(String.join(",", idx.getFields()));
                sql.append(")");
            }
        }
        sql.append(") ENGINE=").append(request.getEngine() == null ? "InnoDB" : request.getEngine());
        sql.append(" DEFAULT CHARSET=").append(request.getCharset() == null ? "utf8mb4" : request.getCharset());
        if (request.getTableComment() != null && !request.getTableComment().isEmpty()) {
            sql.append(" COMMENT='").append(request.getTableComment()).append("'");
        }
        tableInfoMapper.createTable(sql.toString());
    }
}